package com.ls.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ls.rbac.entity.Role;
import com.ls.rbac.entity.UserRole;
import com.ls.rbac.mapper.RoleMapper;
import com.ls.rbac.service.IRolePermissionService;
import com.ls.rbac.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ls.rbac.service.IUserRoleService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liusheng
 * @since 2025--06--28
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Resource
    private IRolePermissionService rolePermissionService;

    @Resource
    private IUserRoleService userRoleService;

    @Override
    public IPage<Role> getRolePage(Page<Role> page, Role role) {
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        if (role != null) {
            if (StringUtils.hasText(role.getRoleName())) {
                queryWrapper.like(Role::getRoleName, role.getRoleName());
            }
            if (StringUtils.hasText(role.getRoleCode())) {
                queryWrapper.like(Role::getRoleCode, role.getRoleCode());
            }
        }
        return this.page(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveRoleWithPermissions(Role role, List<Integer> permissionIds) {
        role.setDeleted((byte) 0);
        boolean saved = this.save(role);
        if (saved && permissionIds != null && !permissionIds.isEmpty()) {
            rolePermissionService.saveRolePermissions(role.getId(), permissionIds);
        }
        return saved;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateRoleWithPermissions(Role role, List<Integer> permissionIds) {
        boolean updated = this.updateById(role);
        if (updated && permissionIds != null) {
            boolean b = rolePermissionService.saveRolePermissions(role.getId(), permissionIds);
            if (!b) {
                throw new RuntimeException("更新角色权限关系失败");
            }
        }
        return updated;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRoleWithPermissionsAndUserRole(Integer roleId) {
        try {
            rolePermissionService.removeByRoleId(roleId);
        } catch (Exception e) {
            throw new RuntimeException("删除角色权限关系失败: " + e.getMessage());
        }
        List<UserRole> userRoles = userRoleService.list(
                new LambdaQueryWrapper<UserRole>()
                        .eq(UserRole::getRoleId, roleId));

        if (userRoles != null && !userRoles.isEmpty()) {
            throw new RuntimeException("该角色已被用户使用，无法删除，请先解除用户与角色的关联");
        }
        return this.removeById(roleId);
    }

    public List<Role> getRolesByUserId(Integer userId) {
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId, userId);
        List<UserRole> userRoles = userRoleService.list(queryWrapper);
        if (userRoles == null || userRoles.isEmpty()) {
            return List.of();
        }
        List<Integer> roleIds = userRoles.stream()
                .map(UserRole::getRoleId)
                .toList();
        LambdaQueryWrapper<Role> roleQueryWrapper = new LambdaQueryWrapper<>();
        roleQueryWrapper.in(Role::getId, roleIds);
        return this.list(roleQueryWrapper);
    }

}
